package com.suoluo.zenadmin.common.file;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.suoluo.zenadmin.common.Application;
import com.suoluo.zenadmin.common.PathUtil;
import com.suoluo.zenadmin.common.config.SystemConfigHolder;



public final class CompressImageUtils {
	private static final int HOTEL_RESOURCE_DEFAULT_IMG_H = 76;

	private static final int HOTEL_RESOURCE_DEFAULT_IMG_W = 164;
	
	public static final String COMPRESS_PREFIX = "mini";

	private static final Log logger = LogFactory
			.getLog(CompressImageUtils.class);

	/**
	 * 压缩酒店资源的默认图片
	 * 
	 * @param request
	 * @param inputFilePath
	 *            压缩的文件的路径:/upload/images/xxxxx.jpg
	 * @return String 返回被压缩后的图片路径:/upload/images/minixxxxx.jpg
	 */
	public static FileEntry compressHotelResourceDefaultImg(FileEntry fileEntry) {
		return compressImg(fileEntry,
				SystemConfigHolder.getHotelResourceNavImgHeight(),
				SystemConfigHolder.getHotelResourceNavImgWidth());
	}

	private static FileEntry compressImg(
			FileEntry fileEntry, int height, int width) {
		Application a = Application.getInstance();
		String inputFilePath = SystemConfigHolder.getRelativeUploadImageRoot() + fileEntry.getFilePath();
		String abstractFilePath = a.getPath("/")+ inputFilePath;

		File inputFile = new File(abstractFilePath);
		if (!inputFile.exists()) {
			logger.warn("compress file not exists,filePath= " + inputFilePath);
			return null;
		}

		File parentDir = inputFile.getParentFile();

		String outputFileName = SystemConfigHolder.getMiniImgPreffix() + inputFile.getName();
		File outputFile = new File(parentDir, outputFileName);
		try {
			ImageUtils.compressImage(inputFile, outputFile, height, width);
//			int fileNameStartIndex = inputFilePath.lastIndexOf("/") + 1;
			return new FileEntry(fileEntry.getFilePreffix(), outputFileName);
		} catch (Exception e) {
			logger.error("fail to compress img,Make sure that image is in RGB mode", e);
			throw new RuntimeException(
					"fail to compress img,Make sure that image is in RGB mode",
					e);
		}

	}

	public static void main(String[] args) {
		// String filePath = "/upload/hotel/12142143214312.jpg";
		//
		// String outputFilePath = filePath.substring(0,fileNameStartIndex);
		// System.out.println(outputFilePath);
		// File file = new File("D:\\1.jpg");
		// System.out.println(file.getName());
	}
}